package org.client.iot.ui.ble;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.clj.fastble.data.BleDevice;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.client.iot.R;
import org.client.iot.ble.BleTemplate;
import org.client.iot.ble.ModBusTemplate;
import org.client.iot.constant.GlobeDataManager;
import org.client.iot.databinding.ActivityDemoBinding;
import org.client.iot.util.TimeUtils;
import org.tzw.template.base.BaseActivity;

import java.time.LocalDateTime;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;

// ModbusUtils.java
import java.io.ByteArrayOutputStream;





public class DemoActivity extends BaseActivity<ActivityDemoBinding> {
    private BleDevice targetDevice;
    private MaterialDialog materialDialog;

    private String currentCmd = "";//最终下发的指令字符串
    private String[] cmdArray;//指令列表
    private  ArrayAdapter arrayAdapter;
    @Override
    protected void initData() {
        targetDevice = (BleDevice) getIntent().getParcelableExtra("targetDev");
        cmdArray = new String[]{
                "1  标准测量",
                "2  初值清零",
                "3  叠加初值",
                "4  叠加形变",
                "5  老化测量",
                "6  机械复位",
                "7  松开抱闸",
                "8  刷新状态",
                "9  模式切换 调试期",
                "10 模式切换 运行期",
                "11 停止充电",
                "12 开始充电",
                "13 开始探孔",
                "14 模块故障状态",
                "20 工作模式",
                "21 传感器位置",
                "22 主机电量",
        };
    }

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarDemo);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//添加默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true);
        mRoot.txtHealthDevName.setText(StrUtil.format("设备名称1:{}", targetDevice.getName()));
        mRoot.txtHealthDevMac.setText(StrUtil.format("设备mac:{}", targetDevice.getMac()));
        mRoot.txtHealthConnectState.setText(StrUtil.format("连接状态:{}", BleTemplate.getInstance().isConnected()?"已连接":"未连接"));
        mRoot.btnConnect.setText(BleTemplate.getInstance().isConnected()?"断开连接":"连接");

        mRoot.editTextTextMultiLine.setMovementMethod(ScrollingMovementMethod.getInstance());

        arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,cmdArray);
        mRoot.spinnerCmdList.setAdapter(arrayAdapter);
    }

    @Override
    protected void initListener() {
        mRoot.btnConnect.setOnClickListener(v -> {
            if(BleTemplate.getInstance().isConnected()){
                BleTemplate.getInstance().cancelConnect();
            }else{
                BleTemplate.getInstance().start(targetDevice);
            }
        });
        mRoot.spinnerCmdList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
                Log.d(getTagName(), "setOnItemClickListener: postion:"+index);
                byte[] modbusCmd = null;//最终下发的目标指令
                //@TODO 这里的index对应的就是cmdArray中指令类型的顺序
                /*1 标准测量*/
                if (index == 0) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01,   // 设备地址
                            0x06,   // 功能码
                            0x100, // 寄存器起始地址   标准测量
                            0x0001  // 写入寄存器内容
                    );//这里就对应的cmdArray中的指令一，后面以此类推
                }
                /*2 初值清零*/
                else if (index == 1) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x101, 0x0001);
                }
                /*3 叠加初值*/
                else if (index == 2) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x102, 0x0001);
                }
                /*4 叠加形变*/
                else if (index == 3) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x103, 0x0001);
                }
                /*"5  老化测量",  */
                else if (index == 4) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x104, 0x0001);
                }
                /*"6  机械复位",*/
                else if (index == 5) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x105, 0x0001);
                }
                /* "7  松开抱闸",*/
                else if (index == 6) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x106, 0x0001);
                }
                /*"8  刷新状态",*/
                else if (index == 7) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x107, 0x0001);
                }
                /* "9  模式切换 调试期",*/
                else if (index == 8) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x108, 0x0000);
                }
                /* "10 模式切换 运行期",*/
                else if (index == 9) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x108, 0x0001);
                }

                /* "11 停止充电",*/
                else if (index == 10) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x109, 0x0000);
                }

                /* "12 开始充电",*/
                else if (index == 11) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x109, 0x0001);
                }
                /*"13 开始探孔" 置孔深,转换为mm为单位  默认 20m*/
                else if (index == 12) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x10A, 20000);
                }

                /*"14 模块故障状态" 读取模块故障 读取一个寄存器*/
                else if (index == 13) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x03, 0x10B, 0x0001);
                }
                /*"20 工作模式",*/
                else if (index == 14) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x200, 0x0001);
                }

                /*"21 传感器位置",*/
                else if (index == 15) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x201, 0x0001);
                }
                /*"22 主机电量",*/
                else if (index == 16) {modbusCmd = ModBusTemplate.createModbusCommand(
                        0x01, 0x06, 0x202, 0x0001);
                }




                currentCmd = modbusCmd == null?"": ModBusTemplate.bytesToHex(modbusCmd);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        mRoot.btnSend.setOnClickListener(v -> {
            if(!BleTemplate.getInstance().isConnected()){
                showToastShort("设备未连接");
                return;
            }
            String cmd = mRoot.etCmd.getText().toString();
            if(StrUtil.isEmpty(cmd)&&StrUtil.isEmpty(currentCmd)){
                showToastShort("请输入指令!");
                return;
            }
            if(StrUtil.isNotEmpty(currentCmd)) {
                BleTemplate.getInstance().write(currentCmd);
            }else{
                BleTemplate.getInstance().write(cmd);
            }
        });

        /*发送MODBUS 指令 btn_sendmodbus*/
        mRoot.btnSendmodbus.setOnClickListener(v -> {
            if(!BleTemplate.getInstance().isConnected()){
                showToastShort("设备未连接");
                return;
            }

            // 1. 构造指令
            byte[] modbusCmd =  ModBusTemplate.createModbusCommand(
                    0x01,   // 设备地址
                    0x06,   // 功能码
                    0x100, // 寄存器起始地址   标准测量
                    0x0001  // 写入寄存器内容
            );

           // String cmd = new String(modbusCmd); // 使用平台默认编码
            //String cmd = "123456";

            String cmd =  ModBusTemplate.bytesToHex(modbusCmd);
            showToastShort(cmd);
//            if(StrUtil.isEmpty(cmd)){
//                showToastShort("请输入指令!");
//                return;
//            }

            //BleTemplate.getInstance().write(cmd);
            BleTemplate.getInstance().write(cmd);
        });

        GlobeDataManager.notifyLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                String source = mRoot.editTextTextMultiLine.getText().toString();

                mRoot.editTextTextMultiLine.setText(source+"\n"+StrUtil.format("时间:{},接收到的内容:{}", TimeUtils.getTime(),s));
                int scrollAmount = mRoot.editTextTextMultiLine.getLayout().getLineTop(mRoot.editTextTextMultiLine.getLineCount())
                        - mRoot.editTextTextMultiLine.getHeight();
                if (scrollAmount > 0) {
                    mRoot.editTextTextMultiLine.scrollTo(0, scrollAmount);
                } else {
                    mRoot.editTextTextMultiLine.scrollTo(0, 0);
                }
            }
        });
        GlobeDataManager.bluetoothProfileLiveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer status) {
                if(status == BluetoothProfile.STATE_CONNECTING){
                    materialDialog = new MaterialDialog.Builder(DemoActivity.this)
                            .content(getString(R.string.common_connecting))
                            .progress(true, 0) // 第一个参数为true表示启用进度条，第二个参数为0表示进度条是不确定的
                            .show();
                    return;
                }
                if(materialDialog!=null){
                    materialDialog.dismiss();
                    materialDialog = null;
                }
                mRoot.txtHealthConnectState.setText(StrUtil.format("连接状态:{}", status == BluetoothProfile.STATE_CONNECTED?"已连接":"未连接"));
                mRoot.btnConnect.setText( status == BluetoothProfile.STATE_CONNECTED?"断开连接":"连接");
            }
        });
    }
}